<?php

namespace App\Store\Controllers\Goods;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Common\Services\Store\Common as StoreCommon;


use App\Common\Services\CommonExcelExport;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Basic\GoodsCategory;
use Maatwebsite\Excel\Facades\Excel;
use App\Store\Services\Excel\DownloadTemp;
use Illuminate\Support\Facades\DB;

use App\Store\Models\Goods\GoodsGlodprice;
use App\Store\Validate\Goods\GoodsGlodprice as ValidateGoodsGoodsGlodprice;

/**
 * 金价管理信息
 */
class GoodsGlodpriceController extends Controller
{

    /**
     * 金价管理
     */
    public function getlist(Request $request)
    {
        $list = GoodsGlodprice::getList($request);
        return response()->json(['code' => '000', 'msg' => '获取成功', 'data' => $list]);

    }

    public function getinfo(Request $request)
    {
        $id = intval($request->id);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsGlodprice::with(['storeinfo','categoryinfo'])->where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }
        return response()->json(['code' => '000', 'msg' => '获取成功','data'=>['info'=>$info]]);

    }

    /**
     * 金价维护,单类别多门店
     */
    public function domaintenance(Request $request){

        $req_data = $request->only(['store_ids','goods_category_name','back_company_price','sales_price','sales_limit_min_price','old_recovery_price','old_goods_workfee','date_str','remark']);
        $Validate = new ValidateGoodsGoodsGlodprice();
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $store_ids = $req_data['store_ids'];
        $store_ids = is_array($store_ids) ? $store_ids : (is_array(json_decode($store_ids, true)) ? json_decode($store_ids, true) : []);


        if (count($store_ids) <= 0) {

            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $back_company_price=isset($req_data['back_company_price'])?intval($req_data['back_company_price']):0;
        $sales_price=isset($req_data['sales_price'])?intval($req_data['sales_price']):0;
        $sales_limit_min_price=isset($req_data['sales_limit_min_price'])?intval($req_data['sales_limit_min_price']):0;
        $old_recovery_price=isset($req_data['old_recovery_price'])?intval($req_data['old_recovery_price']):0;
        $old_goods_workfee=isset($req_data['old_goods_workfee'])?intval($req_data['old_goods_workfee']):0;
        $date_str=(isset($req_data['date_str']) && strtotime($req_data['date_str'])>0)?$req_data['date_str']:date('Y-m-d');

        $remark=isset($req_data['remark'])?strval($req_data['remark']):'';
        $ins_data=[];
        foreach ($store_ids as $store_id) {
            $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id'],'is_del'=>1])->first();
            if (!$storeinfo) {
                return response()->json(['code' => '001', 'msg' => '无效门店参数']);
            }
            $goodscategoryinfo=GoodsCategory::where(['cp_id'=>$accountinfo['cp_id'],'store_id'=>$store_id,'category_name'=>$req_data['goods_category_name'],'is_del'=>1])->first();

            if(empty($goodscategoryinfo)){
                return response()->json(['code' => '001', 'msg' => $storeinfo->store_name.'不存在品类:'.$req_data['goods_category_name']]);
            }
            $isexist=GoodsGlodprice::where(['cp_id' => $cp_id,'store_id'=>$store_id, 'goods_category_id'=>$goodscategoryinfo->id,'is_del' => 1,'date_str'=>$date_str])->first();
            if($isexist){
                return response()->json(['code' => '001', 'msg' => $storeinfo->store_name.$date_str.$goodscategoryinfo->category_name.'金价已存在']);
            }
//            if($sales_price<=0 || $back_company_price<=0 || $old_recovery_price<=0 || $old_goods_workfee<=0){//任何价格小于等于0，则取历史价格
//                $lastprice=GoodsGlodprice::where(['cp_id' => $cp_id,'store_id'=>$store_id, 'goods_category_id'=>$goodscategoryinfo->id,'is_del' => 1])->orderBy('date_str','desc')->first();
//                if(!$lastprice){
//                    return response()->json(['code' => '001', 'msg' => $storeinfo->store_name.$date_str.$goodscategoryinfo->category_name.'找不到历史金价']);
//                }
//                $sales_price=$lastprice->sales_price;
//                $sales_limit_min_price=$lastprice->sales_limit_min_price;
//                $back_company_price=$lastprice->back_company_price;
//                $old_recovery_price=$lastprice->old_recovery_price;
//                $old_goods_workfee=$lastprice->old_goods_workfee;
//            }

            $ins_data[] = [
                'cp_id'=>$cp_id,
                'store_id'=>$store_id,
                'goods_category_id'=>$goodscategoryinfo->id,
                'sales_price'=>$sales_price,
                'sales_limit_min_price'=>$sales_limit_min_price,
                'back_company_price'=>$back_company_price,
                'old_recovery_price'=>$old_recovery_price,
                'old_goods_workfee'=>$old_goods_workfee,
                'date_str'=>$date_str,
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
                'update_at' => time(),
                'remark'=>$remark,
            ];
        }
        GoodsGlodprice::insert($ins_data);
        return response()->json(['code' => '000', 'msg' => '金价维护成功']);


    }

    /**
     * 编辑
     */

    public function dopostedit(Request $request){
        $req_data = $request->only(['id','back_company_price','sales_price','sales_limit_min_price','old_recovery_price','old_goods_workfee','date_str','remark']);
        $Validate = new ValidateGoodsGoodsGlodprice('edit');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsGlodprice::where(['id' => $req_data['id'], 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        $isexist=GoodsGlodprice::where([['id','<>',$req_data['id']]])->where(['cp_id' => $cp_id, 'goods_category_id'=>$info->goods_category_id,'is_del' => 1,'date_str'=>$req_data['date_str']])->first();

        if($isexist){
            return response()->json(['code' => '001', 'msg' => '该日期金价已存在']);
        }
        $data=$req_data;
        unset($data['id']);
        $data['update_at'] = time();
        $data['update_account_id'] = $accountinfo['id'];
        $data['update_account_real_name'] = $accountinfo['real_name'];
        GoodsGlodprice::where(['id' => $req_data['id']])->update($data);
        return response()->json(['code' => '000', 'msg' => '编辑成功']);
    }

    /**
     * 金价管理删除
     */
    public function dopostdel(Request $request)
    {
        $id = intval($request->id);

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $info = GoodsGlodprice::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '参数错误']);
        }

        GoodsGlodprice::where(['id' => $id, 'cp_id' => $cp_id, 'is_del' => 1])->update(['is_del'=>2,'del_at'=>time()]);
        return response()->json(['code' => '000', 'msg' => '删除成功']);

    }

    /**
     * 批量新增，单门店多类别
     */
    public function dopostbatchadd(Request $request)
    {
        $req_data = $request->only(['store_id','goods_category_ids','back_company_price','sales_price','sales_limit_min_price','old_recovery_price','old_goods_workfee','date_str','remark']);
        $Validate = new ValidateGoodsGoodsGlodprice('dopostbatchadd');
        if (!$Validate->check($req_data)) {
            return response()->json(['code' => '001', 'msg' => $Validate->getError()]);
        }
        $goods_category_ids = $req_data['goods_category_ids'];
        $goods_category_ids = is_array($goods_category_ids) ? $goods_category_ids : (is_array(json_decode($goods_category_ids, true)) ? json_decode($goods_category_ids, true) : []);


        if (count($goods_category_ids) <= 0) {

            return response()->json(['code' => '001', 'msg' => '无效类别参数']);
        }

        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $store_id=$req_data['store_id'];
        $storeinfo = SiteStore::where(['id' => $store_id, 'cp_id' => $accountinfo['cp_id'],'is_del'=>1])->first();
        if (!$storeinfo) {
            return response()->json(['code' => '001', 'msg' => '无效门店参数']);
        }

        $back_company_price=isset($req_data['back_company_price'])?intval($req_data['back_company_price']):0;
        $sales_price=isset($req_data['sales_price'])?intval($req_data['sales_price']):0;
        $sales_limit_min_price=isset($req_data['sales_limit_min_price'])?intval($req_data['sales_limit_min_price']):0;
        $old_recovery_price=isset($req_data['old_recovery_price'])?intval($req_data['old_recovery_price']):0;
        $old_goods_workfee=isset($req_data['old_goods_workfee'])?intval($req_data['old_goods_workfee']):0;

        $date_str=(isset($req_data['date_str']) && strtotime($req_data['date_str'])>0)?$req_data['date_str']:date('Y-m-d');

        $remark=isset($req_data['remark'])?strval($req_data['remark']):'';
        $ins_data=[];
        foreach ($goods_category_ids as $goods_category_id) {
            $goodscategoryinfo = GoodsCategory::where(['id' => $goods_category_id,'store_id'=>$store_id, 'cp_id' => $accountinfo['cp_id'],'is_del'=>1])->first();
            if (empty($goodscategoryinfo)) {
                return response()->json(['code' => '001', 'msg' => '无效品类参数']);
            }
            $isexist=GoodsGlodprice::where(['cp_id' => $cp_id,'store_id'=>$store_id, 'goods_category_id'=>$goods_category_id,'is_del' => 1,'date_str'=>$date_str])->first();
            if($isexist){
                return response()->json(['code' => '001', 'msg' => $storeinfo->store_name.$date_str.'【'.$goodscategoryinfo->category_name.'】金价已存在']);
            }
//            if($sales_price<=0 || $back_company_price<=0 || $old_recovery_price<=0 || $old_goods_workfee<=0 || $sales_limit_min_price <= 0){
//                //任何价格小于等于0，则取历史价格
//                $lastprice=GoodsGlodprice::where(['cp_id' => $cp_id,'store_id'=>$store_id, 'goods_category_id'=>$goodscategoryinfo->id,'is_del' => 1])
//                    ->orderBy('date_str','desc')
//                    ->first();
//                if(!$lastprice){
//                    return response()->json(['code' => '001', 'msg' => $storeinfo->store_name.$date_str.'【'.$goodscategoryinfo->category_name.'】找不到历史金价']);
//                }
//                $sales_price=$lastprice->sales_price;
//                $sales_limit_min_price=$lastprice->sales_limit_min_price;
//                $back_company_price=$lastprice->back_company_price;
//                $old_recovery_price=$lastprice->old_recovery_price;
//                $old_goods_workfee=$lastprice->old_goods_workfee;
//            }

            $ins_data[] = [
                'cp_id'=>$cp_id,
                'store_id'=>$store_id,
                'goods_category_id'=>$goods_category_id,
                'sales_price'=>$sales_price,
                'sales_limit_min_price'=>$sales_limit_min_price,
                'back_company_price'=>$back_company_price,
                'old_recovery_price'=>$old_recovery_price,
                'old_goods_workfee'=>$old_goods_workfee,
                'date_str'=>$date_str,
                'create_account_id' => $accountinfo['id'],
                'update_account_id' => $accountinfo['id'],
                'create_account_real_name' => $accountinfo['real_name'],
                'update_account_real_name' => $accountinfo['real_name'],
                'create_at' => time(),
                'update_at' => time(),
                'remark'=>$remark,
            ];
        }
        GoodsGlodprice::insert($ins_data);
        return response()->json(['code' => '000', 'msg' => '金价批量新增成功']);
    }

    /**
     * 复制数据
     */
    public function dopostcopy(Request $request)
    {
        $req_data=$request->only(['target_date_start','target_date_end','choose_date']);
        $accountinfo = StoreCommon::getCurrentAccountinfo($request);
        $cp_id = $accountinfo['cp_id'];
        $datalist=GoodsGlodprice::where(['cp_id'=>$cp_id,'date_str'=>$req_data['choose_date'],'is_del'=>1])->select(['cp_id','store_id','goods_category_id','back_company_price','sales_price','sales_limit_min_price','old_recovery_price','old_goods_workfee'])->get()->toArray();
        $target_date_start=strtotime($req_data['target_date_start']);
        $target_date_end=strtotime($req_data['target_date_end']);
        $ins_data=[];
        $days=ceil(($target_date_end-$target_date_start)/(24*3600));
        for($i=0;$i<=$days;$i++){
            $time=$target_date_start+$i*24*3600;
            if($time>=$target_date_start && $time<=$target_date_end){
                $date=date('Y-m-d',$time);
                foreach($datalist as $val){
                    $item=$val;
                    $item['date_str']=$date;
                    $item['create_account_id'] = $accountinfo['id'];
                    $item['update_account_id'] = $accountinfo['id'];
                    $item['create_account_real_name'] = $accountinfo['real_name'];
                    $item['update_account_real_name'] = $accountinfo['real_name'];
                    $item['create_at'] = time();
                    $item['update_at'] = time();
                    $ins_data[] = $item;
                }


            }else{
                continue;
            }
        }

        GoodsGlodprice::insert($ins_data);
        return response()->json(['code' => '000', 'msg' => '金价复制成功']);
    }

    /**
     * 导出数据
     */
    public function doexport(Request $request)
    {
        $list = GoodsGlodprice::getList($request)['list'];

        $exceldata = [];
        $row = [
            ['start_sotre'=>'金价管理列表'],
            [
                'store_name' => '门店名称',
                'goods_category_name'=>'商品类别',
                'back_company_price'=>'返厂金价',
                'sales_price'=>'销售牌价',
                'sales_limit_min_price'=>'最低销售牌价',
                'old_recovery_price'=>'旧料回收价',
                'old_goods_workfee'=>'折旧工费',
                'date_str'=>'日期',
                'create_account_real_name'=>'创建人',
                'create_at'=>'创建时间',
                'update_account_real_name'=>'更新人',
                'update_at'=>'更新时间',
            ]
        ];
        foreach ($list as $val) {
            $exceldata[] = [
                'store_name' => $val['storeinfo']['store_name'],
                'goods_category_name' => $val['categoryinfo']['category_name'],
                'back_company_price'=>$val['back_company_price']/100,
                'sales_price'=>$val['sales_price']/100,
                'sales_limit_min_price'=>$val['sales_limit_min_price']/100,
                'old_recovery_price'=>$val['old_recovery_price']/100,
                'old_goods_workfee'=>$val['old_goods_workfee']/100,
                'date_str'=>$val['date_str'],
                'create_account_real_name'=>$val['create_account_real_name'],
                'create_at'=>date('Y-m-d H:i:s',$val['create_at']),
                'update_account_real_name'=>$val['update_account_real_name'],
                'update_at'=>date('Y-m-d H:i:s',$val['update_at'])
            ];
        }

        $filename = '金价管理信息导出_' . time() . '.xlsx';
        return Excel::download(new CommonExcelExport($row, $exceldata), $filename);

    }


}
